using System;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Security.Permissions;

namespace KingPang.hohoBlog.API
{
    /// <summary>
    /// This class implements the API for posting blog to LiveJournal
    /// </summary>
    public sealed class LiveJournal
    {
        private CookieCollection Cookies;
        private System.Net.CookieContainer cookieContainer;

        public LiveJournal()
        {
            Cookies = new CookieCollection();
            cookieContainer = new System.Net.CookieContainer();
        }

        public bool Login(string username, string password)
        {
            try
            {
                // Prepare the HttpWebRequest to send data to LiveJournal.com
                string url = string.Format("http://www.livejournal.com/login.bml");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040707 Firefox/0.9.2";
                request.Method = "POST";
                request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                request.KeepAlive = true;
                request.ContentType = @"application/x-www-form-urlencoded";
                request.Referer = string.Format("http://www.livejournal.com/login.bml?nojs=1");
                request.CookieContainer = cookieContainer;

                // Send the log-in data
                string postData = string.Format("response=&user={0}&password={1}&expire=close&bindip=no&action%3Alogin=Log+in...", username, password);
                request.Method = "POST";
                byte[] postBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(postData);
                request.ContentLength = postBuffer.Length;
                Stream postDataStream = request.GetRequestStream();
                postDataStream.Write(postBuffer, 0, postBuffer.Length);
                postDataStream.Close();

                // Get the response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);

                // Add the cookie to this instance of object, such that the cookies can be reused
                // for next request
                Cookies.Add(response.Cookies);

                // Read the response from the stream
                Encoding enc = System.Text.Encoding.UTF8;
                StreamReader responseStream = new StreamReader(response.GetResponseStream(), enc, true);

                string responseHtml = responseStream.ReadToEnd();
                response.Close();
                responseStream.Close();

                // For debug purpose, print out the cookies received from LiveJournal.com
                foreach (Cookie c in response.Cookies)
                {
                    Debug.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                }

                // Check if log-in is successful
                string successString = "you are now logged in to LiveJournal.com";
                if (responseHtml.IndexOf(successString) >= 0)
                {
                    // log-in successfully
                    return true;
                }
                else
                {
                    // log-in failed
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool AddBlog(string aSubject, string aBody)
        {
            try
            {
                // Prepare the HttpWebRequest to send data to LiveJournal.com
                string url = string.Format("http://www.livejournal.com/update.bml");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040707 Firefox/0.9.2";
                request.Method = "POST";
                request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                request.KeepAlive = true;
                request.ContentType = @"application/x-www-form-urlencoded";
                request.Referer = string.Format("http://www.livejournal.com/update.bml");
                request.CookieContainer = cookieContainer;

                // Send the blog data
                DateTime dt = DateTime.Now;
                string postData = string.Format("user=&password=&date_ymd_mm={0}&date_ymd_dd={1}&date_ymd_yyyy={2}&hour={3}&min={4}&subject={5}&event={6}&switched_rte_on=&security=public&event_format=auto&prop_current_music=&prop_current_moodid=&prop_current_mood=&usejournal=&action%3Aupdate=Update+Journal&comment_settings=&prop_opt_screening=", dt.Month, dt.Day, dt.Year, dt.Hour, dt.Minute, aSubject, aBody);
                request.Method = "POST";
                byte[] postBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(postData);
                request.ContentLength = postBuffer.Length;
                Stream postDataStream = request.GetRequestStream();
                postDataStream.Write(postBuffer, 0, postBuffer.Length);
                postDataStream.Close();

                // Get the response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);

                // Add the cookie to this instance of object, such that the cookies can be reused
                Cookies.Add(response.Cookies);

                // Read the response from the stream
                Encoding enc = System.Text.Encoding.UTF8;
                StreamReader responseStream = new StreamReader(response.GetResponseStream(), enc, true);

                string responseHtml = responseStream.ReadToEnd();
                response.Close();
                responseStream.Close();

                // For debug purpose, print out the cookies received from LiveJournal.com		
                foreach (Cookie c in response.Cookies)
                {
                    Debug.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                }

                // blog finished
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
